﻿using System.Text.Json;

namespace planning_lite
{
	public partial class MainPage : ContentPage
	{

		public static List<TaskItem> Tasks { get; set; } = new List<TaskItem>();
		public static TaskFilter Filter { get; set; } = new TaskFilter();
		public static Settings Settings { get; set; } = new Settings();
		public delegate void TasksUpdate();
		public static TasksUpdate? OnTasksUpdate = null;
		public static TaskPoster? poster = null;

		public static TaskItem? currFocusedTask { get; set; } = null;

		public MainPage()
		{
			InitializeComponent();
			LoadTasks();
			ShowTasks();
			OnTasksUpdate += DeleteUntitledTasks;
			OnTasksUpdate += SaveTasks;
			OnTasksUpdate += ShowTasks;
			this.BindingContext = this;
			Settings = Settings.ReadCurrentSettings();
			poster = new TaskPoster();
		}

		protected override async void OnAppearing()
		{
			base.OnAppearing();
			await PrepareTasksSync();
		}

		private async Task PrepareTasksSync()
		{
			if (poster is not null) {
				try
				{
					if (string.IsNullOrWhiteSpace(Settings.taskServerLocation))
					{
						return;
						// 当服务器地址为空时，不进行同步
					}
					await poster.PostJsonAsync<TaskData>(Settings.taskServerLocation,
						new TaskData { TaskLists = Tasks, UserName = Settings.userName });
				}
				catch (Exception ex)
				{
					await DisplayAlert("Error", $"将任务同步到服务器 {Settings.taskServerLocation} 失败，原因是 {ex.Message}\n\n详细信息：{ex}", "好吧");
				}
			}
		}

		public void LoadTasks()
		{
			string filePath = Path.Combine(FileSystem.AppDataDirectory, "tasks.json");
			try
			{
				if (File.Exists(filePath))
				{
					string jsonContent = File.ReadAllText(filePath);
					var taskData = JsonSerializer.Deserialize<TaskData>(jsonContent);
					if (taskData?.TaskLists != null)
					{
						Tasks = taskData.TaskLists;
					}
				}
				else
				{
					var defaultTaskData = new TaskData { TaskLists = new List<TaskItem>() };
					string jsonContent = JsonSerializer.Serialize(defaultTaskData);
					File.WriteAllText(filePath, jsonContent);
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine($"Error loading tasks: {ex.Message}");
				Dispatcher.Dispatch(async () =>
				{
					await DisplayAlert("Error", $"读取任务列表时失败：{ex.Message}", "好吧");
				});
			}
		}

		public void SaveTasks()
		{
			string filePath = Path.Combine(FileSystem.AppDataDirectory, "tasks.json");
			try
			{
				var taskData = new TaskData { TaskLists = Tasks };
				string jsonContent = JsonSerializer.Serialize(taskData);
				File.WriteAllText(filePath, jsonContent);
			}
			catch (Exception ex)
			{
				Console.WriteLine($"Error saving tasks: {ex.Message}");
				Dispatcher.Dispatch(async () =>
				{
					await DisplayAlert("Error", $"保存任务列表时失败：{ex.Message}", "好吧");
				});
			}
			_ = PrepareTasksSync();
		}

		public void ShowTasks()
		{
			var filteredTasks = Filter.ApplyFilter(Tasks);
			TasksCollectionView.ItemsSource = filteredTasks.Select(task => new TaskItemViewModel
			{
				Original = task,
				Title = task.Title,
				Description = task.Description.Length > 50 ? task.Description.Substring(0, 47) + "..." : task.Description,
				DueDate = task.DueDate.HasValue ? task.DueDate.Value.ToString("yyyy-MM-dd") : "无截止时间",
				Priority = "优先级 " + task.Priority.ToString() + " - " + (task.CheckNeeded
					? (task.LastCheckedDate.HasValue && task.LastCheckedDate.Value.Date == DateTime.Today
						? "已打卡" : "需要打卡") : "长期任务"),
				Status = task.IsCompleted ? "已完成" : (task.IsObsolete ? "已废弃" : "进行中"),
				StatusColor = GetStatusColor(task),
			}).ToList();
		}

		private Color GetStatusColor(TaskItem task)
		{
			// 已完成的任务 - 淡绿色
			if (task.IsCompleted)
				return Colors.LightGreen;
			// 废弃的任务 - 灰色
			if (task.IsObsolete)
				return Colors.LightGray;
			// 如果有截止日期
			if (task.DueDate.HasValue)
			{
				TimeSpan timeLeft = task.DueDate.Value - DateTime.Today;
				// 超过截止时间 - 紫色
				if (timeLeft.TotalDays <= 0)
					return Colors.Purple;
				// 距离截止时间在一天之内 - 红色
				if (timeLeft.TotalDays <= 1)
					return Colors.Red;
				// 距离截止时间在三天之内 - 橙色
				if (timeLeft.TotalDays <= 3)
					return Colors.Orange;
				// 距离截止时间在一星期之内 - 黄色
				if (timeLeft.TotalDays <= 7)
					return Colors.Yellow;
			}
			// 进行中的任务 - 淡蓝色
			return Colors.LightBlue;
		}

		public void DeleteUntitledTasks()
		{
			Tasks.RemoveAll(task => string.IsNullOrWhiteSpace(task.Title) || (task.Title == "新任务" && task.Description == "待添加描述"));
		}

		private async void OnFilterClicked(object sender, EventArgs e)
		{
			await Navigation.PushAsync(new FilterPage(Filter));
		}

		private async void OnSettingsClicked(object sender, EventArgs e)
		{
			await Navigation.PushAsync(new SettingsPage());
		}

		private async void OnItemTapped(object sender, TappedEventArgs e)
		{
			if (e.Parameter is TaskItemViewModel taskViewModel)
			{
				await ProcessTaskSelection(taskViewModel);
			}
		}

		private async void OnTaskSelected(object sender, SelectionChangedEventArgs e)
		{
			if (e.CurrentSelection.Count > 0)
			{
				var taskViewModel = e.CurrentSelection[0] as TaskItemViewModel;
				if (taskViewModel != null)
				{
					await ProcessTaskSelection(taskViewModel);
				}
				TasksCollectionView.SelectedItem = null;
			}
		}

		private async Task ProcessTaskSelection(TaskItemViewModel taskViewModel)
		{
			if (taskViewModel?.Original != null)
			{
				var task = taskViewModel.Original;
				string dueDateText = task.DueDate.HasValue
					? $"截止时间: {task.DueDate.Value.ToString("yyyy-MM-dd")}"
					: "无截止时间";
				string priorityText = $"优先级: {task.Priority}";
				string statusText = task.IsCompleted ? "状态: 已完成" : (task.IsObsolete ? "状态: 已废弃" : "状态: 进行中");
				string details = $"{task.Description}\n\n{dueDateText}\n{priorityText}\n{statusText}";

				string action = await DisplayActionSheet(task.Title, "取消", null, "打卡任务", "编辑", "查看详情", (task.IsCompleted ? "标记未完成" : "标记完成"), "标记废弃", "从日志中删除");

				if (action == "打卡任务")
				{
					task.LastCheckedDate = DateTime.Now;
					OnTasksUpdate?.Invoke();
					await DisplayAlert("任务打卡", $"任务 '{task.Title}' 已打卡。", "确定");
				}
				else if (action == "编辑")
				{
					currFocusedTask = task;
					await Navigation.PushAsync(new TaskEditPage());
				}
				else if (action == "查看详情")
				{
					await DisplayAlert(task.Title, details, "确定");
				}
				else if (action == "标记完成")
				{
					task.IsCompleted = true;
					task.IsObsolete = false;
					OnTasksUpdate?.Invoke();
				}
				else if (action == "标记未完成")
				{
					task.IsCompleted = false;
					task.IsObsolete = false;
					OnTasksUpdate?.Invoke();
				}
				else if (action == "标记废弃")
				{
					task.IsObsolete = true;
					task.IsCompleted = false;
					OnTasksUpdate?.Invoke();
				}
				else if (action == "从日志中删除")
				{
					bool confirmDelete = await DisplayAlert("确认删除", $"确定要删除任务 '{task.Title}' 吗？", "是", "否");
					if (confirmDelete)
					{
						Tasks.Remove(task);
						OnTasksUpdate?.Invoke();
					}
				}
			}
		}

		private async void OnAddNewTaskClicked(object sender, EventArgs e)
		{
			TaskItem NewTask = new TaskItem
			{
				Title = "新任务",
				Description = "待添加描述",
				DueDate = DateTime.Now.AddDays(7),
				CreatedDate = DateTime.Now
			};
			currFocusedTask = NewTask;
			Tasks.Add(NewTask);

			var taskEditPage = new TaskEditPage();
			await Navigation.PushAsync(taskEditPage);
		}
	}

	public class TaskItemViewModel
	{
		public TaskItem Original { get; set; } = new TaskItem();
		public string Title { get; set; } = string.Empty;
		public string Description { get; set; } = string.Empty;
		public string DueDate { get; set; } = string.Empty;
		public string Priority { get; set; } = string.Empty;
		public string Status { get; set; } = string.Empty;
		public Color StatusColor { get; set; } = Colors.Transparent;
		public string CheckStatus { get; set; } = "长期任务";
	}

}